package com.ciquan.server.controller;

import com.ciquan.server.bean.Message;
import com.ciquan.server.bean.UserInfo;
import com.ciquan.server.bean.WorksInfo;
import com.ciquan.server.service.MessageService;
import com.ciquan.server.service.UserInfoService;
import com.ciquan.server.service.WorksInfoService;
import com.ciquan.server.util.MD5Utils;
import com.ciquan.server.util.URLConnUtils;
import com.ciquan.server.util.json.JsonMapper;
import com.ciquan.server.util.web.Result;
import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.ServletRequestUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.*;

/**
 * Created by bjliwei2014 on 2015/2/27.
 */
@Controller
@RequestMapping("/message")
public class MessageController extends AbstractController{

    @Resource
    private MessageService messageService;

    @Resource
    private UserInfoService userInfoService;

    @Resource
    private WorksInfoService worksInfoService;

    private static JsonMapper jsonMapper = JsonMapper.buildNormalBinder();

    @RequestMapping(value = "/works")
    public ModelAndView works(ModelMap modelMap) {
        List<Integer> worksIds = messageService.selectWorks();
        List<WorksInfo> worksInfos = new ArrayList<WorksInfo>();
        for(Integer worksId : worksIds) {
            WorksInfo worksInfo = worksInfoService.selectById(worksId);
            if(worksInfo != null) {
                worksInfos.add(worksInfo);
                UserInfo userInfo = userInfoService.selectById(worksInfo.getUserid());
                if(userInfo != null) {
                    worksInfo.setUsername(userInfo.getName());
                }
            }
        }
        modelMap.put("worksInfos", worksInfos);
        return new ModelAndView("message", modelMap);
    }

    @RequestMapping(value = "/users", produces = "text/plain;charset=UTF-8")
    @ResponseBody
    public String users(HttpServletRequest request) {
        Result result = new Result();
        int worksId = ServletRequestUtils.getIntParameter(request, "worksId", 0);
        int userId = ServletRequestUtils.getIntParameter(request, "userId", 0);
        List<Integer> userIds = messageService.selectUsers(worksId, userId);
        List<UserInfo> userInfos = new ArrayList<UserInfo>();
        for(Integer id : userIds) {
            UserInfo userInfo = userInfoService.selectById(id);
            if(userInfo != null) {
                Message message = messageService.selectLastMessage(worksId, id);
                userInfo.setLastMessage(message);
                userInfos.add(userInfo);
            }
        }

        Collections.sort(userInfos, new Comparator<UserInfo>() {
            @Override
            public int compare(UserInfo userInfo1, UserInfo userInfo2) {
                return userInfo2.getLastMessage().getcTime()
                        .compareTo(userInfo1.getLastMessage().getcTime());
            }
        });

        Map<String, Object> map = new HashMap<String, Object>();
        map.put("userInfos", userInfos);
        result.setSuccess(true);
        result.setStatusmsg("获取用户成功");
        result.setData(map);

        return result.toString();
    }

    @RequestMapping(value = "/session", produces = "text/plain;charset=UTF-8")
    @ResponseBody
    public String session(HttpServletRequest request) {
        Result result = new Result();
        int worksId = ServletRequestUtils.getIntParameter(request, "worksId", 0);
        int userId = ServletRequestUtils.getIntParameter(request, "userId", 0);
        List<Message> messages = messageService.selectMessage(worksId, userId);
        result.setSuccess(true);
        result.setStatusmsg("获取用户成功");
        result.setData(messages);
        return result.toString();
    }

    @RequestMapping(value = "/send", produces = "text/plain;charset=UTF-8")
    @ResponseBody
    public String send(HttpServletRequest request) {
        Result result = new Result();
        int worksId = ServletRequestUtils.getIntParameter(request, "worksId", 0);
        int userId = ServletRequestUtils.getIntParameter(request, "userId", 0);
        String content = ServletRequestUtils.getStringParameter(request, "content", "");
        WorksInfo worksInfo = worksInfoService.selectById(worksId);
        Integer uid = worksInfo.getUserid();
        boolean flag = sendMessage(worksId, uid, userId, content);
        result.setSuccess(flag);
        return result.toString();
    }

    private boolean sendMessage(Integer worksId, Integer send, Integer receive, String  content) {
        List<URLConnUtils.Part> params = new ArrayList<URLConnUtils.Part>();
        URLConnUtils.addMultiParam(params, "works_id", worksId.toString());
        URLConnUtils.addMultiParam(params, "receive_userid", receive.toString());
        URLConnUtils.addMultiParam(params, "content", content);
        URLConnUtils.addMultiParam(params, "u_pic", null);
        URLConnUtils.addMultiParam(params, "userid", send.toString());
        URLConnUtils.addMultiParam(params, "hash", getUserHash(send.toString()));

        String res = URLConnUtils.doMultiPost("http://127.0.0.1/api/sendMessage", params);
        Map<String, Object> resultMap = jsonMapper.fromJson(res, Map.class);
        if(resultMap.get("errno") != null) {
            if(StringUtils.equals("0", resultMap.get("errno").toString())) {
                return true;
            }
        }

        return false;
    }
}
